package com.kingyun.gpsinspection.purificationservice.services.jsm.innerservice.impl.version;

import com.alibaba.fastjson.JSONObject;
import com.cqhilink.api.common.utils.UniqueUtil;
import com.cqhilink.api.common.utils.date.DateStyle;
import com.cqhilink.api.common.utils.date.DateUtil;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.jsm.SingleWorkStepMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.jsm.VersionMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.jsm.JsmWorkCellInfoMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.jsm.JsmWorkCellInstanceMapper;
import com.kingyun.gpsinspection.purificationservice.facade.model.jsm.*;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.operateunit.JsmOperateUnitService;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.operatingunitform.JsmOperatingUnitFormService;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.version.JsmVersionService;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.workCellDataSet.JsmIWorkCellDataSetService;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.workcellinfo.JsmIRelatedDocService;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.workcellinfo.JsmIRiskInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * Created by huangxueqian on 2017/2/13/013.
 * 版本管理服务实现类
 * 用于新增、查询、删除、系统中的各种版本
 */

public class JsmVersionServiceImpl implements JsmVersionService {

    @Autowired
    private VersionMapper versionMapper;



    @Autowired
    private JsmOperateUnitService operateUnitService ;

    @Autowired
    private JsmIRiskInfoService iRiskInfoService ;

    @Autowired
    private JsmIRelatedDocService relatedDocService;

    @Autowired
    private JsmWorkCellInfoMapper jsmWorkCellInfoMapper;

    @Autowired
    private JsmWorkCellInstanceMapper jsmWorkCellInstanceMapper;

    @Autowired
    private JsmOperatingUnitFormService operatingUnitFormService ;

    @Autowired
    private SingleWorkStepMapper singleWorkStepMapper;

    @Autowired
    private JsmIWorkCellDataSetService workCellDataSetService;

    /**
     * 新增版本信息
     * @param version
     * @return
     * @throws Exception
     */
    @Override
    public Version addVersion(Version version,EmployeeVo employee) throws Exception {
        if(version!=null) {
            if (version.getVersionId() == null) {
                version.setVersionId(UniqueUtil.uuid());
            }

            version.setCreatorId(employee.getEmployeeId());
            version.setCreateTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM));

            version.setModifierId(employee.getEmployeeId());
            version.setModifyTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM));
            if(version.getStatus() == null ){
                version.setStatus(BigDecimal.valueOf(0d));
            }
        }
        versionMapper.insertSelective(version);
        return version ;
    }





    /**
     *
     * @param version
     * @return 删除版本信息
     * @throws Exception
     */
    @Override
    public Integer delVersion(Version version) throws Exception {

        return versionMapper.deleteByPrimaryKey(version.getVersionId());
    }

    /**
     * 查询版本信息
     * @param version
     * @return
     */
    @Override
    public Version queryVersion(Version version) {
        return versionMapper.selectByPrimaryKey(version);
    }

    /**
     * 查询最新版本
     * @param relatedId
     * @return
     */
    @Override
    public Version queryMaxVersion(String relatedId) {

        return versionMapper.selectMaxByRelatedId(relatedId);
    }

    @Override
    public List<Version> queryVersionList(String relatedId) {
        return versionMapper.queryVersionList(relatedId);
    }


    @Override
    public JSONObject table(Version version) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("total",versionMapper.queryCount(version))  ;
        jsonObject.put("rows",versionMapper.queryList(version))   ;
        return jsonObject;
    }

    /**
     * 关于操作单元或者一站一案新增版本后的操作
     * @param  version
     * @param  isWorkCell
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,readOnly = false,rollbackFor = Exception.class)
    public Integer addVersion(Version version, boolean isWorkCell,EmployeeVo employee) throws Exception {
        Version max = versionMapper.selectMaxByRelatedId(version.getRelatedId());
        // 当前是操作单元 则查询操作单元
        if(max!=null){
            version.setVersionNumber(max.getVersionNumber().add(new BigDecimal(0.01)));
        }else{
            version.setVersionNumber(new BigDecimal(1));
        }
        int resInt = 0 ;
        try {
            Version vs =  addVersion(version,employee);
            versionAfter(vs,isWorkCell,max,employee);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
        /**
         * 操作单元新版本新增后操作 ；
         */
        return resInt;
    }

    /**
     *  操作单元；新增问题版本
     *  1:查询当前版本；复制当前版本或者无版本的操作步骤；新增到版本
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void versionAfter(Version version ,boolean isWorkCell,Version max,EmployeeVo employee) throws Exception{
        BigDecimal oldVersion = null ;
        if(isWorkCell){
            WorkCellInfo workCellInfo =   jsmWorkCellInfoMapper.selectByPrimaryKey(version.getRelatedId());
            if(workCellInfo != null && workCellInfo.getStepVersion() != null){
                oldVersion  = workCellInfo.getStepVersion();
            }
        }else{
            WorkCellInstanceVo workCellInstanceVo =  jsmWorkCellInstanceMapper.selectByPrimaryKey(version.getRelatedId());
            if(workCellInstanceVo != null && workCellInstanceVo.getStepVersion() != null){
                oldVersion  = workCellInstanceVo.getStepVersion();
            }
        }
        if(oldVersion==null){
            oldVersion = new BigDecimal(1);
        }


        /**
         * 第一步：操作表单， 逻辑处理
         */
            int count = operatingUnitFormService.cloneOperateForm(version, isWorkCell, oldVersion, employee);
            if(count==-1){
                throw new RuntimeException("特性值没有绑定设备");
            }

        /**
         * 第二步 : 操作步骤
         */
        try {
            operateUnitService.cloneStep(version,oldVersion,employee);
        } catch (Exception e) {
            e.printStackTrace();
        }

        /**
         * 第三步骤 ：文档配置
         */
        try {
            relatedDocService.cloneDoc(version ,isWorkCell,oldVersion,employee);
        } catch (Exception e) {
            e.printStackTrace();
        }


        /**
         * 第四步骤 ：管理数据集
         * 还未做
         */
        try{
            workCellDataSetService.cloneDataSet(version ,isWorkCell,oldVersion,employee);
        }catch (Exception e){
            e.printStackTrace();
        }

        /**
         * 更新版本问题
         */
        if(isWorkCell){
            WorkCellInfo workCellInfo = jsmWorkCellInfoMapper.selectByPrimaryKey(version.getRelatedId());
            workCellInfo.setStepVersion(version.getVersionNumber());
            jsmWorkCellInfoMapper.updateByPrimaryKeySelective(workCellInfo);
        }else{
            WorkCellInstance workCellInstance = jsmWorkCellInstanceMapper.selectByPrimaryKey(version.getRelatedId());
            workCellInstance.setStepVersion(version.getVersionNumber());
            jsmWorkCellInstanceMapper.updateByPrimaryKeySelective(workCellInstance);
        }


    }

}
